package com.b2c.repository.tao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.b2c.entity.result.PagingResponse;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.entity.tao.TaoGoodsUpgradeEntity;

@Repository
public class TaoGoodsUpgradeRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public ResultVo<Long> addRecord(Integer shopId,Long goodsId, String oldTitle, Integer oldSales, String newTitle, String remark,
            String date) {

        String sql = "INSERT INTO dc_tao_goods_upgrade_record (goodsId,oldTitle,newTitle,remark,date,oldSales,shopId) value (?,?,?,?,?,?,?)";
        jdbcTemplate.update(sql, goodsId, oldTitle, newTitle, remark, date, oldSales,shopId);
        return new ResultVo<>(EnumResultVo.SUCCESS, "SUCCESS");
    }

    @Transactional
    public PagingResponse<TaoGoodsUpgradeEntity> getList(Integer shopId, Integer pageIndex, Integer pageSize,
            String goodsId) {

        List<Object> params = new ArrayList<>();
        StringBuilder sb = new StringBuilder("SELECT SQL_CALC_FOUND_ROWS  tg.* ");
        sb.append(" FROM dc_tao_goods_upgrade_record ").append(" as tg ");

        sb.append(" WHERE tg.shopId = ?  ");
        params.add(shopId);

        if (StringUtils.hasText(goodsId)) {
            sb.append(" AND (tg.goodsId = ? ) ");
            params.add(goodsId);
    
        }

        sb.append(" ORDER BY tg.date DESC ");

        sb.append("  LIMIT ?,?");
        params.add((pageIndex - 1) * pageSize);
        params.add(pageSize);

        var list = jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(TaoGoodsUpgradeEntity.class),
                params.toArray(new Object[params.size()]));

        int totalSize = getTotalSize();

        return new PagingResponse<>(pageIndex, pageSize, totalSize, list);
    }

    protected int getTotalSize() {
        return jdbcTemplate.queryForObject("SELECT FOUND_ROWS() as row_num;", int.class);
    }
}
